package com.study.map;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @Author refeal
 * @Date 2021/5/25 10:28
 * @Version 1.0
 * @Description 基于jvm map缓存工具类
 */
public class CacheProvider {
  //存放缓存的集合（定义一个全局的map）
  private final static Map<String,CacheData> cacheDatas = new ConcurrentHashMap<>();
  //定时器线程池，用于清除过期缓存
  private final static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
  /**
   *
   * 获取缓存
   * @param key
   * @param <T>
   * @return
   *
   * */
  public synchronized <T> T get(String key) {
    CacheData  cacheData = cacheDatas.get(key);
    return  cacheData == null ? null : (T) cacheData.data;
  }
  /**
   * 添加缓存,默认不失效
   * @param key  key
   * @param value  value
   * */
  public synchronized void  put(String key,Object value){
    //cacheDatas.put(key,new CacheData(value,-1L));
    this.put(key,value,-1L);
  }
  /**
   * 添加缓存,需要设置失效时间
   * @param key   key
   * @param value   value
   * @param  expire   expire 单位：毫秒 -1表示不失效
   * */
  public synchronized void  put(String key,Object value,Long expire){
    //清除原数据
    cacheDatas.remove(key);
    if (expire > 0){
      cacheDatas.put(key,new CacheData((value),expire));
    }else {
      cacheDatas.put(key,new CacheData(value,-1L));
    }
  }

  /**
   * 删除缓存
   *
   * @param key
   * @param <T>
   * @return
   * **/
  public synchronized <T> T remove(String  key){
    //清除缓存数据
    CacheData cacheData = cacheDatas.remove(key);
    return  cacheData == null ? null : (T) cacheData.data;
  }
  /**
   *
   * 查询当前缓存的键值对数量
   *
   * */
  public synchronized int size(){
    return  cacheDatas.size();
  }

  /**
   * 缓存实体类
   * */
  public  class CacheData {
    //缓存数据
    public Object data;
    //失效时间
    public Long expire;

    public CacheData(Object data,Long expire){
      this.data = data;
      this.expire = expire;
    }

  }
}
